/*
 * GStreamer
 * Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
 * Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
 * Copyright (C) 2022 root <<user@hostname.org>>
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 * Alternatively, the contents of this file may be used under the
 * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
 * which case the following provisions apply instead of the ones
 * mentioned above:
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/**
 * SECTION:element-dsoftbussrc
 *
 * FIXME:Describe dsoftbussrc here.
 *
 * <refsect2>
 * <title>Example launch line</title>
 * |[
 * gst-launch -v -m fakesrc ! dsoftbussrc ! fakesink silent=TRUE
 * ]|
 * </refsect2>
 */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <gst/gst.h>
#include <gst/base/gstbasesrc.h>
#include "gstdsoftbussrc.h"

GST_DEBUG_CATEGORY_STATIC (gst_dsoftbussrc_debug);
#define GST_CAT_DEFAULT gst_dsoftbussrc_debug
Gstdsoftbussrc *g_filter = NULL;
/* Filter signals and args */
enum
{
  /* FILL ME */
  LAST_SIGNAL
};

enum
{
  PROP_0,
  PROP_SILENT,
  PROP_PKGNAME,
  PROP_SESSIONNAME,
  PROP_PUBID,
};

/* the capabilities of the inputs and outputs.
 *
 * describe the real formats here.
 */
// static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
//     GST_PAD_SINK,
//     GST_PAD_ALWAYS,
//     GST_STATIC_CAPS ("ANY")
//     );

static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
    GST_PAD_SRC,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("ANY")
    );

#define gst_dsoftbussrc_parent_class parent_class
G_DEFINE_TYPE (Gstdsoftbussrc, gst_dsoftbussrc, GST_TYPE_ELEMENT);

GST_ELEMENT_REGISTER_DEFINE (dsoftbussrc, "dsoftbussrc", GST_RANK_NONE,
    GST_TYPE_DSOFTBUSSRC);

static void gst_dsoftbussrc_set_property (GObject * object,
    guint prop_id, const GValue * value, GParamSpec * pspec);
static void gst_dsoftbussrc_get_property (GObject * object,
    guint prop_id, GValue * value, GParamSpec * pspec);

static void gst_dsoftbussrc_dispose (GObject * object);

static GstStateChangeReturn
dsoftbussrc_change_state (GstElement * element, GstStateChange transition);

/* GObject vmethod implementations */

// static gboolean gst_dsoftbussrc_start (GstBaseSrc * src);

/* initialize the dsoftbussrc's class */

static void
gst_dsoftbussrc_class_init (GstdsoftbussrcClass * klass)
{
  GObjectClass *gobject_class;
  GstElementClass *gstelement_class;

  gobject_class = (GObjectClass *) klass;
  gstelement_class = (GstElementClass *) klass;

  gst_element_class_set_details_simple (gstelement_class,
      "dsoftbussrc",
      "FIXME:Generic",
      "FIXME:Generic Template Element", "root <<user@hostname.org>>");

  gst_element_class_add_pad_template (gstelement_class,
      gst_static_pad_template_get (&src_factory));

  gobject_class->set_property = gst_dsoftbussrc_set_property;
  gobject_class->get_property = gst_dsoftbussrc_get_property;
  gobject_class->dispose = gst_dsoftbussrc_dispose;
  gstelement_class->change_state = dsoftbussrc_change_state;

  g_object_class_install_property (gobject_class, PROP_SILENT,
      g_param_spec_boolean ("silent", "Silent", "Produce verbose output ?",
          FALSE, G_PARAM_READWRITE));
  g_object_class_install_property (gobject_class, PROP_SESSIONNAME,
      g_param_spec_string ("session_name", "session_name", "dsoftbus session name",
          "test", G_PARAM_READWRITE));
  g_object_class_install_property (gobject_class, PROP_PKGNAME,
      g_param_spec_string ("pkg_name", "pkg_name", "dsoftbus pkg name",
          "test", G_PARAM_READWRITE));
  g_object_class_install_property (gobject_class, PROP_PUBID,
      g_param_spec_int ("publish_id", "publish_id", "dsoftbus publish id",
          1, 65535, 123, G_PARAM_READWRITE));


  /*gst_element_class_set_details_simple (gstelement_class,
      "dsoftbussrc",
      "FIXME:Generic",
      "FIXME:Generic Template Element", "root <<user@hostname.org>>");

  gst_element_class_add_pad_template (gstelement_class,
      gst_static_pad_template_get (&src_factory));*/
  // gst_element_class_add_pad_template (gstelement_class,
  //     gst_static_pad_template_get (&sink_factory));
}

/* start and stop processing, ideal for opening/closing the resource */

static int SessionOpened(int sessionId, int result)
{
	printf("[SessionOpened]CB: session %d open ret=%d\n", sessionId, result);
	return 0;
}

static void SessionClosed(int sessionId)
{
	printf("[SessionClosed]CB: session %d closed\n", sessionId);
}

//static int number = 0;
//#define MSG1 "takeoff\n"
//#define MSG2 "land\n"
//#define MSG3 "startVideo\n"
//#define MSG4 "endVedio\n"
static void ByteRecived(int sessionId, const void *data, unsigned int dataLen)
{
	printf("[ByteRecived]CB: session %d received %u\n", sessionId, dataLen);
	GstBuffer *buffer = gst_buffer_new_memdup(data, dataLen);
  gst_pad_push (g_filter->srcpad, buffer);
  
//  number ++;
//  if (number % 400 == 0)
//  {
//    SendBytes(sessionId,  MSG1, strlen(MSG1));
//  }
//  else if (number % 300 == 0)
//  {
//    SendBytes(sessionId,  MSG2, strlen(MSG2));
//  }
//  else if (number % 200 == 0)
//  {
//    SendBytes(sessionId,  MSG3, strlen(MSG3));
//  }
}

static void MessageReceived(int sessionId, const void *data, unsigned int dataLen)
{
	printf("[MessageReceived]CB: session %d received %u bytes message=%s\n", sessionId, dataLen, (const char *)data);
}

static const ISessionListener sessionCB = {
	.OnSessionOpened = SessionOpened,
	.OnSessionClosed = SessionClosed,
	.OnBytesReceived = ByteRecived,
	.OnMessageReceived = MessageReceived,
};

static GstStateChangeReturn
dsoftbussrc_change_state (GstElement * element, GstStateChange transition)
{
  Gstdsoftbussrc *filter = GST_DSOFTBUSSRC (element);
  GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
  int m_ret;
  switch (transition) {
    case GST_STATE_CHANGE_NULL_TO_READY:
      break;
    case GST_STATE_CHANGE_READY_TO_PAUSED:
      m_ret = PublishServiceInterface(filter->publish_id);
      if (m_ret) {
          printf("PublishService fail, ret=%d\n", m_ret);
	  UnPublishService(filter->pkg_name, filter->publish_id);
          return m_ret;
      }

      m_ret = CreateSessionServer(filter->pkg_name, filter->session_name, &sessionCB);
      if (m_ret) {
	  RemoveSessionServer(filter->pkg_name, filter->session_name);
	  UnPublishService(filter->pkg_name, filter->publish_id);
          printf("CreateSessionServer fail, ret=%d\n", m_ret);
          return m_ret;
      }
      break;
    case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
      break;
    case GST_STATE_CHANGE_READY_TO_NULL:
      RemoveSessionServer(filter->pkg_name, filter->session_name);
      UnPublishService(filter->pkg_name, filter->publish_id);
    default:
      break;
 }
 return ret;
}

/* initialize the new element
 * instantiate pads and add them to element
 * set pad callback functions
 * initialize instance structure
 */
static void
gst_dsoftbussrc_init (Gstdsoftbussrc * filter)
{
  GST_DEBUG_OBJECT(filter, "%s", __FUNCTION__);
  filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
  GST_PAD_SET_PROXY_CAPS (filter->srcpad);
  gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
  filter->silent = FALSE;
  filter->pkg_name = "gstreamer";
  filter->session_name = "gstreamer";
  filter->publish_id = 123;
  g_filter = filter;
  return;
}

static void
gst_dsoftbussrc_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
{
  Gstdsoftbussrc *filter = GST_DSOFTBUSSRC (object);

  GST_DEBUG_OBJECT(filter, "%s", __FUNCTION__);
  switch (prop_id) {
    case PROP_SILENT:
      filter->silent = g_value_get_boolean (value);
      break;
    case PROP_SESSIONNAME:
      filter->session_name = g_value_dup_string(value);
      break;
    case PROP_PKGNAME:
      filter->pkg_name = g_value_dup_string(value);
      break;
    case PROP_PUBID:
      filter->publish_id = g_value_get_int(value);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_dsoftbussrc_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec)
{
  Gstdsoftbussrc *filter = GST_DSOFTBUSSRC (object);

  GST_DEBUG_OBJECT(filter, "%s", __FUNCTION__);
  switch (prop_id) {
    case PROP_SILENT:
      g_value_set_boolean (value, filter->silent);
      break;
    case PROP_SESSIONNAME:
      g_value_set_string(value, filter->session_name);
      break;
    case PROP_PKGNAME:
      g_value_set_string(value, filter->pkg_name);
      break;
    case PROP_PUBID:
      g_value_set_int(value, filter->publish_id);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_dsoftbussrc_dispose (GObject * object)
{
  Gstdsoftbussrc *filter = GST_DSOFTBUSSRC (object);
  GST_DEBUG_OBJECT(object, "%s", __FUNCTION__);
}

/* entry point to initialize the plug-in
 * initialize the plug-in itself
 * register the element factories and other features
 */
static gboolean
dsoftbussrc_init (GstPlugin * dsoftbussrc)
{
  /* debug category for filtering log messages
   *
   * exchange the string 'Template dsoftbussrc' with your description
   */
  GST_DEBUG_OBJECT(dsoftbussrc, "%s", __FUNCTION__);
  GST_DEBUG_CATEGORY_INIT (gst_dsoftbussrc_debug, "dsoftbussrc",
      0, "Template dsoftbussrc");

  return GST_ELEMENT_REGISTER (dsoftbussrc, dsoftbussrc);
}

/* PACKAGE: this is usually set by meson depending on some _INIT macro
 * in meson.build and then written into and defined in config.h, but we can
 * just set it ourselves here in case someone doesn't use meson to
 * compile this code. GST_PLUGIN_DEFINE needs PACKAGE to be defined.
 */
#ifndef PACKAGE
#define PACKAGE "myfirstdsoftbussrc"
#endif

/* gstreamer looks for this structure to register dsoftbussrcs
 *
 * exchange the string 'Template dsoftbussrc' with your dsoftbussrc description
 */
GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
    GST_VERSION_MINOR,
    dsoftbussrc,
    "dsoftbussrc",
    dsoftbussrc_init,
    PACKAGE_VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)
